import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useLayerStore } from '../store/layerStore';

/**
 * 图层管理组合式函数
 * @param {Object} fabricCanvas - fabric.js 画布实例引用
 * @returns {Object} 图层管理相关的状态和方法
 */
export function useLayers(fabricCanvas) {
  const layerStore = useLayerStore();
  const canvasInitialized = ref(false);
  
  // 初始化监听器
  onMounted(() => {
    if (fabricCanvas.value) {
      setupCanvasListeners();
      canvasInitialized.value = true;
    }
  });
  
  // 移除监听器
  onUnmounted(() => {
    if (canvasInitialized.value && fabricCanvas.value) {
      removeCanvasListeners();
    }
  });
  
  /**
   * 设置画布监听器以跟踪对象变化
   */
  const setupCanvasListeners = () => {
    const canvas = fabricCanvas.value;
    
    // 选择对象时
    canvas.on('selection:created', handleObjectSelection);
    canvas.on('selection:updated', handleObjectSelection);
    canvas.on('selection:cleared', () => {
      layerStore.selectLayer(null);
    });
    
    // 对象添加/移除时
    canvas.on('object:added', handleObjectAdded);
    canvas.on('object:removed', handleObjectRemoved);
    
    // 对象修改时
    canvas.on('object:modified', handleObjectModified);
  };
  
  /**
   * 移除画布监听器
   */
  const removeCanvasListeners = () => {
    const canvas = fabricCanvas.value;
    
    canvas.off('selection:created', handleObjectSelection);
    canvas.off('selection:updated', handleObjectSelection);
    canvas.off('selection:cleared');
    
    canvas.off('object:added', handleObjectAdded);
    canvas.off('object:removed', handleObjectRemoved);
    
    canvas.off('object:modified', handleObjectModified);
  };
  
  /**
   * 处理对象选择事件
   * @param {Object} options - 事件选项
   */
  const handleObjectSelection = (options) => {
    const selected = options.selected[0];
    if (selected) {
      const layerId = selected.id || '';
      layerStore.selectLayer(layerId);
    }
  };
  
  /**
   * 处理对象添加事件
   * @param {Object} options - 事件选项
   */
  const handleObjectAdded = (options) => {
    const object = options.target;
    if (!object.id) {
      object.id = Date.now().toString();
    }
    
    // 获取对象类型
    let type = 'object';
    if (object.type === 'textbox' || object.type === 'text') {
      type = 'text';
    } else if (object.type === 'image') {
      type = 'image';
    } else if (object.type === 'rect') {
      type = 'rectangle';
    } else if (object.type === 'circle') {
      type = 'circle';
    } else if (object.type === 'triangle') {
      type = 'triangle';
    } else if (object.type === 'line') {
      type = 'line';
    } else if (object.type === 'path') {
      type = 'path';
    }
    
    // 获取对象名称
    let name;
    if (type === 'text') {
      name = object.text.substring(0, 10) + (object.text.length > 10 ? '...' : '');
    } else {
      name = `${type.charAt(0).toUpperCase() + type.slice(1)} ${layerStore.layers.length + 1}`;
    }
    
    // 添加到图层存储
    const layerId = layerStore.addLayer({
      name,
      type,
      fabricObject: object,
      visible: true,
      locked: false,
      id: object.id
    });
    
    // 设置对象的id为图层id
    object.id = layerId;
  };
  
  /**
   * 处理对象移除事件
   * @param {Object} options - 事件选项
   */
  const handleObjectRemoved = (options) => {
    const object = options.target;
    if (object && object.id) {
      layerStore.deleteLayer(object.id);
    }
  };
  
  /**
   * 处理对象修改事件
   * @param {Object} options - 事件选项
   */
  const handleObjectModified = (options) => {
    const object = options.target;
    if (object && object.id) {
      // 更新图层属性
      // 这里可以根据需要更新更多属性
      layerStore.updateLayer(object.id, {
        visible: object.visible,
        opacity: object.opacity
      });
    }
  };
  
  /**
   * 同步图层状态到画布
   */
  const syncLayersToCanvas = () => {
    if (!fabricCanvas.value) return;
    
    const canvas = fabricCanvas.value;
    const layerObjects = canvas.getObjects();
    
    // 更新每个画布对象的可见性等属性
    layerStore.layers.forEach(layer => {
      const object = layerObjects.find(obj => obj.id === layer.id);
      if (object) {
        object.visible = layer.visible;
        object.opacity = layer.opacity;
        
        if (layer.locked) {
          object.selectable = false;
          object.evented = false;
        } else {
          object.selectable = true;
          object.evented = true;
        }
      }
    });
    
    canvas.renderAll();
  };
  
  /**
   * 将画布对象移动到对应的z顺序
   */
  const reorderObjects = () => {
    if (!fabricCanvas.value) return;
    
    const canvas = fabricCanvas.value;
    const objects = canvas.getObjects();
    
    // 创建一个新数组，按照图层存储中的顺序排列对象
    const newOrder = layerStore.layers
      .map(layer => {
        return objects.find(obj => obj.id === layer.id);
      })
      .filter(Boolean);
    
    // 清除画布并按新顺序添加对象
    canvas.clear();
    newOrder.forEach(object => {
      canvas.add(object);
    });
    
    canvas.renderAll();
  };
  
  /**
   * 选择图层并在画布中选中对应对象
   * @param {String} layerId - 图层ID
   */
  const selectLayerAndObject = (layerId) => {
    if (!fabricCanvas.value) return;
    
    layerStore.selectLayer(layerId);
    
    const canvas = fabricCanvas.value;
    const objects = canvas.getObjects();
    
    // 清除当前选择
    canvas.discardActiveObject();
    
    if (layerId) {
      // 查找并选择对象
      const object = objects.find(obj => obj.id === layerId);
      if (object) {
        canvas.setActiveObject(object);
      }
    }
    
    canvas.requestRenderAll();
  };
  
  /**
   * 删除选中的图层和对象
   */
  const deleteSelectedLayer = () => {
    if (!fabricCanvas.value) return;
    
    const { selectedLayerId } = layerStore;
    if (!selectedLayerId) return;
    
    const canvas = fabricCanvas.value;
    const objects = canvas.getObjects();
    const object = objects.find(obj => obj.id === selectedLayerId);
    
    if (object) {
      canvas.remove(object);
      layerStore.deleteLayer(selectedLayerId);
      canvas.requestRenderAll();
    }
  };
  
  return {
    // 状态
    layers: computed(() => layerStore.layers),
    selectedLayer: computed(() => layerStore.selectedLayer),
    
    // 方法
    syncLayersToCanvas,
    reorderObjects,
    selectLayerAndObject,
    deleteSelectedLayer
  };
}